//
//  QiniuOSSUtils.swift
//  EasyChat
//
//  Created by vase on 2022/1/20.
//

import UIKit
import Qiniu

class QiniuOSSUtils: NSObject {
    //OSS云存储的BaseUrl
    let baseUrl : String = "http://r5uhhsyw7.hn-bkt.clouddn.com/"

    func simpleUpload(target : UIImage) -> String {
        let startTime = CFAbsoluteTimeGetCurrent()
        let token : String = UserDefaults.standard.string(forKey: "ossToken")!
        let ossManager = QNUploadManager.init()
        let randomName : String = random(15)
        ossManager?.put(target.jpegData(compressionQuality: 1.0), key: "\(randomName).jpeg", token: token, complete: { info, key, response in
            //print(info)
            if info?.statusCode == 200 {
                //成功上传
                let endTime = CFAbsoluteTimeGetCurrent()
                print("总共耗时: ", (endTime-startTime)/1000)
                //print(response)
            }else {
                //上传失败
            }
        }, option: nil)
        return "\(baseUrl)\(randomName).jpeg"
    }
    
    /** 随机字符串的生成*/
    func random(_ count: Int, _ isLetter: Bool = false) -> String {
        
        var ch: [CChar] = Array(repeating: 0, count: count)
        for index in 0..<count {
            
            var num = isLetter ? arc4random_uniform(58)+65:arc4random_uniform(75)+48
            if num>57 && num<65 && isLetter==false { num = num%57+48 }
            else if num>90 && num<97 { num = num%90+65 }
            
            ch[index] = CChar(num)
        }
        
        return String(cString: ch)
    }
}
